package com.hgts.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgts.common.R;
import com.hgts.mapper.EmployeeMapper;
import com.hgts.pojo.Employee;
import com.hgts.pojo.Role;
import com.hgts.pojo.dto.EmployeeDto;
import com.hgts.service.EmployeeService;
import com.hgts.service.IRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hgts.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hgts.utils.RedisConstants.LOGIN_USER_TTL;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IRoleService roleService;
    @Override
    public R<EmployeeDto> getEmployee(Employee employee) {
        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        //password = DigestUtils.md5DigestAsHex(password.getBytes());

        //先通过redis获取用户 如果有直接登入

        //2、根据页面提交的用户名username查询数据库
        Employee emp = employeeMapper.selectEmployee(employee.getUsername());
        //3、如果没有查询到则返回登录失败结果
        if (emp == null){
            return R.error("登录失败");
        }
        //4、密码比对，如果不一致则返回登录失败结果
        if (!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }
        System.out.println("============");
        //7.保存用户信息到redis
        //7.1s随机生成token作为登入令牌
        String token = UUID.randomUUID().toString(true);
        //7.2 将user对象转为HashMap存储
        EmployeeDto employeeDto = BeanUtil.copyProperties(emp, EmployeeDto.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(employeeDto,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue) -> fieldValue.toString()));
        //7.3存储
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        //7.4 设置token有效期
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL, TimeUnit.MINUTES);
        System.out.println("============");
        return R.success(employeeDto,token);

    }

    @Override
    public R<Page> pageInfo(int page, int pageSize, String username) {
        //分页构造器
        Page pageInfo = new Page(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(username),Employee::getUsername,username);

        //执行查询
        this.page(pageInfo, lambdaQueryWrapper);
        return R.success(pageInfo);
    }




    @Override
    @Transactional
    public R<String> addEmployee(Employee employee) {
        //取出角色信息
        Integer roleId = employee.getRoleId();
        //查询角色表获取id 存入角色信息中
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Role::getId,roleId);
        Role one = roleService.getOne(queryWrapper);
        String role = one.getRole();
        employee.setRole(role);
        //存入角色信息
        this.save(employee);
        return R.success("添加角色信息成功");
    }

    @Override
    @Transactional
    public R<Employee> getEmployeeRole(int id) {
        //根据id获取数据
        Employee employee = this.getById(id);
        //获取角色id
        Integer roleId = employee.getRoleId();
        //根据角色id更改角色信息
        Role role = roleService.getById(roleId);
        String roleRole = role.getRole();
        employee.setRole(roleRole);
        return R.success(employee);
    }


}
